package com.yuyou.tas.lesson.controller;

import com.yuyou.tas.lesson.service.ILessonService;
import com.yuyou.tas.lesson.vo.req.ReqLessonAddOrUp;
import com.yuyou.tas.service.api.lesson.dto.LessonDetailDTO;
import com.yuyou.tas.service.api.lesson.dto.LessonPageDTO;
import com.yuyou.tas.service.api.lesson.dto.LessonStatisticDTO;
import com.yuyou.tas.service.api.lesson.entity.Lesson;
import com.yuyou.tas.util.bean.*;
import com.yuyou.tas.util.enums.admin.AuthUserEnums;
import com.yuyou.tas.util.enums.lesson.LessonEnums;
import com.yuyou.tas.util.tool.DefindBeanUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value="LessonController",description="课程操作接口")
@Validated
@RestController
@RequestMapping(value="/api/lesson")
public class LessonController extends BaseController {

	@Autowired
	private ILessonService lessonService;
	
	
	@ApiOperation(value = "查询课程")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "name", value = "课程名字", paramType = "query"),
		@ApiImplicitParam(name = "baseTrimesterId", value = "学期ID", paramType = "query"),
		@ApiImplicitParam(name = "dataSubject", value = "科目ID", paramType = "query"),
		@ApiImplicitParam(name = "baseSectionId", value = "年级ID", paramType = "query"),
		@ApiImplicitParam(name = "baseLevelId", value = "层次ID", paramType = "query"),
		@ApiImplicitParam(name = "status", value = "发布状态:0:未发布,1:已发布,2:发布中,3:发布失败", paramType = "query"),
		@ApiImplicitParam(name = "type", value = "课程类型：0：标准化  1：自定义", paramType = "query") })
	@RequestMapping(value = "/findLessonPage" ,method = {RequestMethod.GET,RequestMethod.POST})
	public ReturnResult<Pagination<LessonPageDTO>> findLessonPage(HttpServletRequest request,  		
	 @Validated @ModelAttribute PageParams pageParams,String name,String baseTrimesterId,String dataSubject,String baseSectionId,
	 String baseLevelId,String status,String type){

	    Map<String, Object> conditions = new HashMap<>();
	    Pagination<LessonPageDTO> queryPgn = new Pagination<>();
	    LoginRedisObj obj = this.getUserObj(request);


    	conditions.put("name", name);
        conditions.put("baseTrimesterId", baseTrimesterId);
        conditions.put("dataSubject", dataSubject);
        conditions.put("baseSectionId", baseSectionId);	 
        conditions.put("baseLevelId", baseLevelId);	 
        conditions.put("status", status);
        conditions.put("type", type);
        //数据权限
        //机构
        if(obj.getIsSystem()){
        	conditions.put("organId",obj.getOrganizationId());
        	//系统管理员忽律课程类型筛选
			conditions.remove("type");
        }else if(!StringUtils.isEmpty(type) && type.equals(String.valueOf(LessonEnums.type.standard.getValue()))){
			//非系统管理员且查询系统课程、过滤对应机构年级科目权限
			conditions.put("permit" , obj.getOrganizationId());

        }else if(!StringUtils.isEmpty(type) && type.equals(String.valueOf(LessonEnums.type.defind.getValue()))){
        	conditions.put("organId",obj.getOrganizationId());
        } else{
			conditions.put("organIdOrType",obj.getOrganizationId());
		}
        
        //科目年级权限
        if(!obj.getIsManager()){
			if(obj.getUserType()==AuthUserEnums.type.teaching.getValue()){
	            conditions.put("subSecLimit" , obj.getUserId());
			}		
        }
              
	    queryPgn.setConditions(conditions);
	    queryPgn.setPageParams(pageParams);
	    int total = lessonService.findLessonCount(queryPgn);
	    queryPgn.setTotal(total);
	    queryPgn.toBePage();
	    if(total > 0){
	        List<LessonPageDTO> list = lessonService.findLessonPageList(queryPgn);
	        queryPgn.setList(list);
	    }
	    return ReturnResult.success(queryPgn);
	}
     
    @ApiOperation(value = "新增或更改课程")
    @RequestMapping(value = "/addOrUpLesson" ,method = RequestMethod.POST)
    public ReturnResult<LessonDetailDTO> addOrUpLesson(HttpServletRequest request,@Validated @ModelAttribute ReqLessonAddOrUp reqLessonAddOrUp) throws Exception{   	
    	LoginRedisObj obj = this.getUserObj(request);
    	Lesson lesson=new Lesson();
    	DefindBeanUtils.copyProperties(reqLessonAddOrUp, lesson); 
    	ResBoolSimpleInfo<LessonDetailDTO> res=lessonService.addOrUpLesson(lesson,obj.getUserId());    	
    	return ReturnResult.returnRes(res);
    }
    
    @ApiOperation(value = "课程详情")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "课程ID", paramType = "query", required = true)})
    @RequestMapping(value = "/detailLesson" ,method = RequestMethod.POST)
    public ReturnResult<LessonDetailDTO> detailLesson(HttpServletRequest request,@NotNull(message="课程ID不能为空")Long id) throws Exception{  
    	LoginRedisObj obj = this.getUserObj(request);
    	ResBoolSimpleInfo<LessonDetailDTO> info=lessonService.detailLesson(id, obj.getOrganizationId(),obj.getUserId());
		info.getData().setHasPer(1);
		//系统课程、但用户非系统管理员且所在机构没有对应科目年级权限
		if(info.getData() != null && !obj.getIsSystem() && LessonEnums.type.standard.getValue() == info.getData().getType()
				&& (obj.getOrganSubSecMap() == null
				|| !obj.getOrganSubSecMap().containsKey(info.getData().getDataSubject())
				|| CollectionUtils.isEmpty(obj.getOrganSubSecMap().get(info.getData().getDataSubject()))
				|| !obj.getOrganSubSecMap().get(info.getData().getDataSubject()).contains(info.getData().getBaseSectionId()))) {
			LessonDetailDTO l = new LessonDetailDTO();
			l.setHasPer(0);
			return ReturnResult.returnRes(true , null , new ResBoolSimpleInfo(true,null,l));
		}

    	return ReturnResult.returnRes(info);
    }
    
    @ApiOperation(value = "发布课程")
	@ApiImplicitParams({
	@ApiImplicitParam(name = "id", value = "课程ID", paramType = "query", required = true)})
    @RequestMapping(value = "/publishLesson" ,method = RequestMethod.POST)
    public ReturnResult<String> publishLesson(HttpServletRequest request,
    		@NotNull(message="课程ID不能为空")Long id) throws Exception{ 
    	LoginRedisObj obj = this.getUserObj(request);
    	ResBoolSimpleInfo<String> res=lessonService.publishLesson(id, LessonEnums.status.pass.getValue(), obj.getOrganizationId(),obj.getUserId());
    	return ReturnResult.returnRes(res);
    }
    
    @ApiOperation(value = "取消发布课程")
	@ApiImplicitParams({
	@ApiImplicitParam(name = "id", value = "课程ID", paramType = "query", required = true)})
    @RequestMapping(value = "/cancelpubLes" ,method = RequestMethod.POST)
    public ReturnResult<String> cancelpubLes(HttpServletRequest request,
    		@NotNull(message="课程ID不能为空")Long id) throws Exception{ 
    	LoginRedisObj obj = this.getUserObj(request);
    	if(!obj.getIsManager()){
        	return ReturnResult.fail3003();
    	}
	    ResBoolSimpleInfo<String> res=lessonService.cancelPublicLesson(obj.getOrganizationId(),id);   	
    	return ReturnResult.returnRes(res);
    }


	@ApiOperation(value = "课程管理（基础设置）")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "baseSectionId", value = "年级 ID", paramType = "query"),
			@ApiImplicitParam(name = "baseTrimesterId", value = "学期 ID", paramType = "query"),
			@ApiImplicitParam(name = "dataSubject", value = "科目 ID", paramType = "query"),
			@ApiImplicitParam(name = "lessonName", value = "课程名称", paramType = "query")
	        }
	)
	@RequestMapping(value = "/lessonStatistic" ,method = RequestMethod.POST)
	public ReturnResult<LessonStatisticDTO> lessonStatistic(HttpServletRequest request,
															@Validated @ModelAttribute PageParams pageParams,
															Long baseSectionId,
															Long baseTrimesterId,
															Long dataSubject,
															String lessonName){
		LoginRedisObj loginObj = this.getUserObj(request);

		Pagination<LessonStatisticDTO> queryPgn = new Pagination<>();

		Map<String, Object> conditions=new HashMap<>();

		conditions.put("authOrganizationId", loginObj.getOrganizationId());
		conditions.put("dataSubject", dataSubject);
		conditions.put("baseSectionId", baseSectionId);
		conditions.put("baseTrimesterId", baseTrimesterId);
		conditions.put("lessonName", lessonName);

		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);
		int total = lessonService.findLessonStatisticCount(queryPgn);
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total > 0){
			queryPgn.setTotal(total);
			List<LessonStatisticDTO> list = lessonService.findLessonStatisticPageList(queryPgn);
			queryPgn.setList(list);
		}
		return ReturnResult.success(queryPgn);
	}


	@ApiOperation(value = "删除课程")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "课程ID", paramType = "query", required = true)})
	@RequestMapping(value = "/delLesson" ,method = RequestMethod.POST)
	public ReturnResult<String> delLesson(HttpServletRequest request,
											  @NotNull(message="课程ID不能为空")Long id){
		LoginRedisObj obj = this.getUserObj(request);
		ResBoolSimpleInfo<String> res=lessonService.delLesson(id , obj.getIsSystem());
		return ReturnResult.returnRes(res);
	}
}
